package com.example.delicioushunter.control.databasecontrol;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.delicioushunter.model.database.BookColumns;
import com.example.delicioushunter.model.database.FoodColumns;
import com.example.delicioushunter.model.database.MaterialInFoodColumns;
import com.example.delicioushunter.model.object.MaterialsInFood;

public class MaterialsInFoodControl {
	private final static String MATERIAL_IN_FOOD_TABLE = "tbl_materials_in_food";

	public void addMaterialsInFood(ArrayList<MaterialsInFood> materials, SQLiteDatabase db) {
		for (MaterialsInFood m : materials) {
			ContentValues values = new ContentValues();
			values.put(MaterialInFoodColumns.MATERIAL_ID, m.getMaterial_id());
			values.put(MaterialInFoodColumns.FOOD_ID, m.getFood_id());
			values.put(MaterialInFoodColumns.DESCRIPTION, m.getDescription());

			db.insert(MATERIAL_IN_FOOD_TABLE, null, values);
		}
		db.close();
		Log.d("Database", "Add materials in food");
	}

	public ArrayList<MaterialsInFood> getAllMaterialsInFood(SQLiteDatabase db, int food_id) {
		ArrayList<MaterialsInFood> materials = new ArrayList<MaterialsInFood>();
		String selectQuery = "SELECT  * FROM " + MATERIAL_IN_FOOD_TABLE + " WHERE "+MaterialInFoodColumns.FOOD_ID+" = "+food_id;
		Cursor cursor = db.rawQuery(selectQuery, null);
		if (cursor.moveToFirst()) {
			do {
				MaterialsInFood m = new MaterialsInFood();
				m.set_id(Integer.parseInt(cursor.getString(0)));
				m.setMaterial_id(Integer.parseInt(cursor.getString(1)));
				m.setFood_id(Integer.parseInt(cursor.getString(2)));
				m.setDescription(cursor.getString(3));

				materials.add(m);
			} while (cursor.moveToNext());
		}
		db.close();
		Log.d("Database", "Get all materials in food");
		return materials;
	}
	
	public void updateAllMaterialsInFood(ArrayList<MaterialsInFood> materials, SQLiteDatabase db) {
		ContentValues values = new ContentValues();
		for (MaterialsInFood m : materials) {
			values.put(MaterialInFoodColumns.DESCRIPTION, m.getDescription());
			db.update(MATERIAL_IN_FOOD_TABLE, values, FoodColumns.ID + " = ?",
					new String[] { String.valueOf(m.get_id()) });
		}
		
		db.close();
		Log.d("Database", "Update food");
	}
	
	public void deleteMaterialonFood(int _id, SQLiteDatabase db) {
		db.delete(MATERIAL_IN_FOOD_TABLE, MaterialInFoodColumns.ID + " = ?",
				new String[] { String.valueOf(_id) });
		db.close();
	}
}
